package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Message;
import service.MessageService;
import service.UserService;
import service.impl.MessageServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * @author gzp
 * @create 2023-01-05 19:09
 */
@WebServlet("/message/list")
public class MessageListServlet extends HttpServlet {

    MessageService messageService = new MessageServiceImpl();
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //以字符流的形式接收数据
        BufferedReader reader = new BufferedReader(req.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        //将接收的数据转换为json对象方便后面获取
        JSONObject jsonObject = JSON.parseObject(json.toString());
        int sid = jsonObject.getInteger("sid");

        //创建一个用来传数据的JSON对象
        JSONObject msg = new JSONObject();

        List<Message> messages = messageService.selectBySid(sid);

        for (Message message : messages) {
            message.setUser(userService.findById(message.getUid()));
        }

        //向前端发送正确的状态已经要跳转的页面
        msg.put("messages", messages);
        resp.getWriter().write(msg.toString());
    }
}
